from hashlib import sha256
import chat.client.gol

def OTP_encryption(plain_txt):
    cipher_txt = ''
    OTP_key = chat.client.gol.get_value("OTP_key")
    hash = sha256(OTP_key.encode()).hexdigest()  # 得到上一条消息的哈希
    while len(plain_txt) >= 64:  # 将消息以64字节为一组分组加密
        temp = plain_txt[0:64]
        res = ''
        for i in range(64):
            res += chr(ord(hash[i]) ^ ord(temp[i]))
        cipher_txt += res
        plain_txt = plain_txt[64:]
    res = ''
    for i in range(len(plain_txt)):
        res += chr(ord(hash[i]) ^ ord(plain_txt[i]))
    cipher_txt += res
    chat.client.gol.set_value("OTP_key", cipher_txt)  # 将密文存入key中
    return cipher_txt


def OTP_decryption(cipher_txt):
    plain_txt = ''
    OTP_key = chat.client.gol.get_value("OTP_key")
    hash = sha256(OTP_key.encode()).hexdigest()  # 得到上一条消息的哈希
    while len(cipher_txt) > 64:  # 将密文以64字节为一组分组解密
        temp = cipher_txt[0:64]
        res = ''
        for i in range(64):
            res += chr(ord(hash[i]) ^ ord(temp[i]))
        plain_txt += res
        cipher_txt = cipher_txt[64:]
    res = ''
    for i in range(len(cipher_txt)):
        res += chr(ord(hash[i]) ^ ord(cipher_txt[i]))
    plain_txt += res
    chat.client.gol.set_value("OTP_key", cipher_txt)  # 将密文存入key中
    return plain_txt
